import axios from "axios";
import { Toast, Dialog } from "vant";
import throwErr from "./throwErr"; // 捕捉服务端http状态码的方法
import { api } from "./config";
import store from "../../store/index";
import router from "../../router/index";
let axios_count = 0; // 请求次数标记

// 添加请求拦截器
axios.interceptors.request.use(
  config => {
    config.timeout = 180 * 1000; //请求响应时间
    config.headers = {
      "Content-Type": "application/json",
      access_token: store.state.userInfo.token || "himyidea_test_token",
      sign: "himyidea_test_sign",
      dkyd_company_type: sessionStorage.is_admin_login
        ? sessionStorage.company_type
        : ""
    };
    axios_count++;
    sessionStorage.axios_count = axios_count;
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);
// 添加响应拦截器
axios.interceptors.response.use(
  response => {
    axios_count--;
    // 成功响应后删除请求URL缓存
    sessionStorage.axios_count = axios_count;
    // 成功请求后loading计算是否关闭
    if (axios_count <= 0) {
      store.commit("TOGGLE_LOADING", false);
    }
    // 接口逻辑处理
    if (response.status === 200) {
      if (response.data.ret_code === "99012") {
        //服务端定义的响应code码为99012时为登录失效
        Dialog.alert({
          title: "提示",
          message: "登录失效，请重新登陆"
        }).then(() => {
          window.location.href = api;
        });
      } else {
        return Promise.resolve(response.data); //使用Promise.resolve 正常响应
      }
      //服务端定义的响应code码为200时请求成功
    } else {
      return Promise.reject(response.data);
    }
  },
  error => {
    axios_count--;
    if (axios_count <= 0) {
      store.commit("TOGGLE_LOADING", false);
      if (error.message !== 400) {
        Toast("请求失败，请检查网络。");
      }
    }
    if (error && error.response) {
      let res = {};
      res.code = error.response.status;
      res.msg = throwErr(error.response.status, error.response); //throwErr 捕捉服务端的http状态码 定义在utils工具类的方法
      return Promise.reject(res);
    }
    return Promise.reject(error);
  }
);
async function axiosJson(
  url,
  data,
  method = "post",
  loading_show = true,
  speCode, // 需要特殊处理的ret_code
  error_go_back = false,
  options = {} // 需要自定义配置axios的
) {
  //暴露 request 给我们好API 管理
  if (loading_show) {
    store.commit("TOGGLE_LOADING", true);
  }
  method = method.toLocaleLowerCase(); //封装RESTful API的各种请求方式
  // url = api + url;
  const paramType = method === "post" ? "data" : "params";
  let res = await axios({
    method,
    url,
    [paramType]: data,
    ...options
  });
  if (!res) return;
  return new Promise((resolve, reject) => {
    if (speCode) {
      // code!=10000 需要特殊处理
      resolve(res);
      return false;
    }
    if (res.ret_code === "10000") {
      resolve(res);
    } else {
      Toast(res.ret_msg || "请求失败，请检查网络。");
      reject(res);
    }
  });
}

const useAxiosJson = {
  install(app) {
    app.config.globalProperties.$axiosJson = axiosJson;
  }
};

export { axiosJson, useAxiosJson };
